import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import Qs from 'qs'
import {VueAxios} from './axios'
import notification from 'ant-design-vue/es/notification'
import {ACCESS_TOKEN} from '@/store/mutation-types'

// 创建 axios 实例
const service = axios.create({
    baseURL: 'http://192.168.0.117:8113', // api base_url
    timeout: 6000 // 请求超时时间
})

const err = (error) => {
    if (error.response) {
        const data = error.response.data;
        const token = Vue.ls.get(ACCESS_TOKEN);
        if (error.response.status === 403) {
            notification.error({
                message: 'Forbidden',
                description: data.message
            })
        }
        if (error.response.status === 401) {
            notification.error({
                message: 'Unauthorized',
                description: 'Authorization verification failed'
            });
            if (token) {
                store.dispatch('Logout').then(() => {
                    setTimeout(() => {
                        window.location.reload()
                    }, 1500)
                })
            }
        }
    }
    return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
    const AccessToken = Vue.ls.get(ACCESS_TOKEN);
    config.headers['DIDI-DADA'] = AccessToken;
    config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    config.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    config.headers.common['X-XSRF-TOKEN'] = false;
    config.paramsSerializer = function (params) {
        return Qs.stringify(params, {arrayFormat: 'brackets'})
    };
    return config
}, err);

// response interceptor
service.interceptors.response.use((response) => {
    const data = response.data;
    if( data.code === 0 ) {
        return response.data;
    }
    if ( data.code === 4 && (data.error === 'Unauthenticated.') ) {
        notification.error({
            message: 'Unauthorized',
            description: 'Authorization verification failed'
        });
        return store.dispatch('Logout').then(() => {
            window.location.reload()
        })
    }
    return response.data;
    return Promise.reject(response);
}, err);

const installer = {
    vm: {},
    install(Vue) {
        Vue.use(VueAxios, service)
    }
};

export {
    installer as VueAxios,
    service as axios
}
